package com.basic.library.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;
import android.util.Base64;
import android.util.Log;
import android.widget.ScrollView;

import com.basic.library.R;
import com.basic.library.base.BaseApplication;
import com.basic.library.base.BaseConstants;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * 图片处理方式
 * 
 * @author gejian 2013-1-24
 */
public class ImageUtils {

	public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
		String SDCARD_MNT = "/mnt/sdcard";
		String SDCARD = "/sdcard";

		String filePath = null;

		String mUriString = mUri.toString();
		mUriString = Uri.decode(mUriString);

		String pre1 = "file://" + SDCARD + File.separator;
		String pre2 = "file://" + SDCARD_MNT + File.separator;

		if (mUriString.startsWith(pre1)) {
			filePath = Environment.getExternalStorageDirectory().getPath()
					+ File.separator + mUriString.substring(pre1.length());
		} else if (mUriString.startsWith(pre2)) {
			filePath = Environment.getExternalStorageDirectory().getPath()
					+ File.separator + mUriString.substring(pre2.length());
		}
		return filePath;
	}

	/*
	 * 图片地址是否存在
	 */
	public static String IsSaveImageFileExist(String url, final int width,
                                              final int height, int scale) {
		// boolean IsImageFileExist = false;
		String result = "";
		String fileDir = ""; // 路径名
		String fileName = ""; // 文件名
		String filePath = ""; // 文件绝对路径
		if (url != null && !url.equals("")) { // 图片地址为空时
			fileName = url.substring(url.lastIndexOf('/') + 1);
			fileDir = BaseConstants.CACHE_SAVE_IMG_PATH;
			filePath = fileDir + fileName;

			if (FileUtils.isHasSDCard()) {
				File file = new File(filePath);
				// 文件存在
				if (file.exists()) {
					// IsImageFileExist = true;
					result = filePath;
				}
			}
		}
		return result;
	}

	/*
	 * 获取图片的旋转
	 */
	public static String getOrientation(Uri mImageCaptureUri) {

		// 不管是拍照还是选择图片每张图片都有在数据中存储也存储有对应旋转角度orientation值
		// 所以我们在取出图片是把角度值取出以便能正确的显示图片,没有旋转时的效果观看
		String orientation = "";
		ContentResolver cr = BaseApplication.getInstance().getContentResolver();
		Cursor cursor = cr.query(mImageCaptureUri, null, null, null, null);// 根据Uri从数据库中找
		if (cursor != null) {
			cursor.moveToFirst();// 把游标移动到首位，因为这里的Uri是包含ID的所以是唯一的不需要循环找指向第一个就是了
			orientation = cursor
					.getString(cursor.getColumnIndex("orientation"));// 获取旋转的角度
			cursor.close();
		}
		return orientation;
	}

	/**
	 * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换 
	 * @param imageUri
	 * @author yaoxing
	 * @date 2014-10-12 
	 */
	@TargetApi(19)
	public static String getImageAbsolutePath(Activity context, Uri imageUri) {
		if (context == null || imageUri == null)
			return null;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
			if (isExternalStorageDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			} else if (isDownloadsDocument(imageUri)) {
				String id = DocumentsContract.getDocumentId(imageUri);
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[] { split[1] };
				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		} // MediaStore (and general)  
		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			// Return the remote address  
			if (isGooglePhotosUri(imageUri))
				return imageUri.getLastPathSegment();
			return getDataColumn(context, imageUri, null, null);
		}
		// File  
		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			return imageUri.getPath();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = { column };
		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is ExternalStorageProvider. 
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is DownloadsProvider. 
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is MediaProvider. 
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check. 
	 * @return Whether the Uri authority is Google Photos. 
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	/*
	 * 获取相机拍照的图片地址
	 */
	public static String getCameraFileName() {
		String picPathString = "";
		Calendar c = Calendar.getInstance();
		String year = String.valueOf(c.get(Calendar.YEAR));
		String month = String.valueOf(c.get(Calendar.MONTH) + 1);
		String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
		String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
		String minute = String.valueOf(c.get(Calendar.MINUTE));
		String second = String.valueOf(c.get(Calendar.SECOND));
		String name = "IMG_" + year + "_" + month + "_" + day + "_" + hour
				+ "_" + minute + "_" + second;
		picPathString = BaseConstants.CACHE_IMG_TEMP_PATH; // 临时图片存储地址
		if (FileUtils.isHasSDCard()) {
			File destDir = new File(picPathString);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}
		}
		picPathString = picPathString + name + ".jpg";
		return picPathString;
	}

	/*
	 * 获取图片的旋转
	 */
	public static String getOrientation(String imgPath) {
		ExifInterface exifInterface;
		try {
			exifInterface = new ExifInterface(imgPath);
			int tag = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION, -1);
			if (tag == ExifInterface.ORIENTATION_ROTATE_90) {// 如果是旋转地图片则先旋转
				return "90";
			} else if (tag == ExifInterface.ORIENTATION_ROTATE_180) {// 如果是旋转地图片则先旋转
				return "180";
			} else if (tag == ExifInterface.ORIENTATION_ROTATE_270) {// 如果是旋转地图片则先旋转
				return "270";
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "0";
	}

	// 第一个参数是图片的路径，第二个参数是获取到的缩略图的宽度，第三个参数是获取到的缩略图的高度
	// 第一个参数是图片的路径，第二个参数是获取到的缩略图的宽度，第三个参数是获取到的缩略图的高度
	public static Bitmap getImageThumbnail(String imagePath, int width,
                                           int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Config.ARGB_4444;
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	/*
	 * 获取Bitmap通过Path
	 */
	public static Bitmap getBitmapByPath(String path) {
		Bitmap bitmap = null;
		if (FileUtils.isHasSDCard()) {
			File file = new File(path);
			if (file.exists()) {
				// if(FileUtils.isImage(path)){
				// 如果内存大于要显示的图片时，才显示
				if (SystemMemoryUtil.getAvailMemory(BaseApplication
						.getInstance().getApplicationContext()) > file.length()) {
					// bitmap=BitmapFactory.decodeFile(path);
					InputStream inputStream = null;
					try {
						inputStream = new FileInputStream(path);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					bitmap = BitmapFactory.decodeStream(inputStream);
				}
				// }
			}
		}
		return bitmap;
	}

	/*
	 * 获取Drawable通过Path
	 */
	public static Drawable getDrawableByPath(String path) {
		Bitmap bitmap = null;
		Drawable drawable = null;
		if (FileUtils.isHasSDCard()) {
			File file = new File(path);
			if (file.exists()) {
				if (FileUtils.isImage(path)) {
					// 如果内存大于要显示的图片时，才显示
					if (SystemMemoryUtil.getAvailMemory(BaseApplication
							.getInstance().getApplicationContext()) > file
							.length()) {
						// bitmap=BitmapFactory.decodeFile(path);
						InputStream inputStream = null;
						try {
							inputStream = new FileInputStream(path);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
						// if(BaseConfig.screenUtils.getWidth()>480){
						// BitmapFactory.Options options=new
						// BitmapFactory.Options();
						// options.inJustDecodeBounds = false;
						// options.inSampleSize = 2; //width，hight设为原来的四分之一
						// bitmap =
						// BitmapFactory.decodeStream(inputStream,null,options);
						// }else{
						// bitmap = BitmapFactory.decodeStream(inputStream);
						// }
						bitmap = BitmapFactory.decodeStream(inputStream);
						drawable = new BitmapDrawable(bitmap);
					}
				}
			}
		}
		return drawable;
	}

	/*
	 * 保存Bitmap图片 isRecycle 是否释放
	 */
	public static boolean saveBitmap(Bitmap bitmap, String path,
                                     boolean isRecycle) throws IOException {
		boolean isSave = false;
		if (bitmap == null) {
			return isSave;
		}
		File file = new File(path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(file);
			if (bitmap.compress(CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
				isSave = true;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 释放bitmap
			if (isRecycle && bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
		return isSave;
	}

	/*
	 * 图片压缩
	 */
	public static File compressImg(File file, int s) {
		Bitmap tmp = null;
		Bitmap tmpBitmap = null;

		long size = s * 1024;
		if (NetworkUtils.getNetworkState() == NetworkUtils.NETWORK_WIFI) {
			size = s * 1024;
		} else {
			size = s/2 * 1024;
		}
		if (!file.exists() || file.length() < size) // 若文件不存在，或者小于500k，则不进行压缩
			return file;

		try {
			String path = BaseConstants.CACHE_IMG_TEMP_PATH;
			File tmpfile = new File(path);
			if (!tmpfile.exists()) {
				tmpfile.mkdirs();
			}
			tmpfile = new File(path, "tmp.jpg");
			Bitmap bm = compressImageByScale(file.getAbsolutePath());
			tmpfile = new File(path + file.getName());

			compressImageBySize(bm, tmpfile);

			if (bm != null && !bm.isRecycled()) {
				bm.recycle();
			}

			// if(orientation != null && !orientation.equals("") &&
			// !orientation.equals("0")){
			// tmp = getBitmapByPath(file.getAbsolutePath());
			// int angle = Integer.parseInt(orientation);
			// Matrix matrix = new Matrix();
			// matrix.setRotate(angle);
			// tmpBitmap = Bitmap.createBitmap(tmp,0,0, tmp.getWidth(),
			// tmp.getHeight(),matrix, true);
			// if(saveBitmap(tmpBitmap, file.getAbsolutePath())){
			// return file;
			// }else{
			// return null;
			// }
			// }
			return tmpfile;
		} catch (Exception e) {
			return null;
		} finally {
			if (tmp != null && !tmp.isRecycled()) {
				tmp.recycle();
			}
			if (tmpBitmap != null && !tmpBitmap.isRecycled()) {
				tmpBitmap.recycle();
			}
		}
	}

	/*
	 * 按文件大小压缩
	 */
	public static void compressImageBySize(Bitmap image, File file) {
		int size = 500 * 1024;
		if (NetworkUtils.getNetworkState() == NetworkUtils.NETWORK_WIFI) {
			size = 500 * 1024;
		} else {
			size = 250 * 1024;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length > size) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 5;// 每次都减少5
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(file);
			image.compress(CompressFormat.JPEG, options, out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/*
	 * 按图片比例压缩
	 */
	public static Bitmap compressImageByScale(String srcPath) {
		String orientation = getOrientation(srcPath);
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = false;
		// 图片比例压缩
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);// 此时返回bm为空

		int w = opts.outWidth;
		int h = opts.outHeight;
		float ww = 640f;// 这里设置宽度为1200f
		if (NetworkUtils.getNetworkState() == NetworkUtils.NETWORK_WIFI) {
			ww = 640f;
		} else {
			ww = 480f;
		}
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		if (w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			w = (int) ww;
			h = opts.outHeight * w / opts.outWidth;
		}
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		Bitmap bmp = Bitmap.createScaledBitmap(bitmap, w, h, false);
		if (orientation != null && !orientation.equals("")
				&& !orientation.equals("0")) {
			int angle = Integer.parseInt(orientation);
			Matrix matrix = new Matrix();
			matrix.setRotate(angle);
			Bitmap tmpBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
					bmp.getHeight(), matrix, true);
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
			if (bmp != null && !bmp.isRecycled()) {
				bmp.recycle();
			}
			return tmpBitmap;
		}
		// 保存调整过宽度的图片
		// saveBitmap(bmp, tmpfile.getAbsolutePath());
		// if(bitmap != null && !bitmap.isRecycled()){
		// bitmap.recycle();
		// }
		return bmp;
	}

	// 将小图放大后，做成圆形图片
	public static byte[] getImage(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 基于HTTP协议连接对象
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream inStream = conn.getInputStream();
			return read(inStream);
		}
		return null;
	}

	public static byte[] read(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();

	}

	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	// 将图片放大一面
	public static Bitmap toImageZoom(Bitmap bitmap, int screenWidth,
                                     int screenHeight) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		int newWidth = (int) (screenWidth / 3);
		int newHeight = (int) (screenHeight / 6);
		// float scaleWidth = ((float) newWidth) / width;
		// float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		if (screenWidth >= 720) {
			matrix.postScale(2, 2);
		} else {
			float scaleWidth = (float) 1;
			float scaleHeight = (float) 1;
			matrix.postScale(scaleWidth, scaleHeight);
		}
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return resizedBitmap;
	}

	/**
	 * bitmap转为base64
	 * 
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * base64转为bitmap
	 * 
	 * @return
	 */

	/*public static Bitmap base64ToBitmap(String base64Data) {
		byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}*/

	// 通过URL得到Bitmap
	public static Bitmap getBitmapFromURL(String path) {
		Bitmap bitmap = null;
		try {
			URL url = new URL(path);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(5000);
			if (connection.getResponseCode() == 200) {
				InputStream is = connection.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	@SuppressLint("NewApi")
	public static Bitmap imageZoom(Bitmap bitmap, double maxSize) {
		// 图片允许最大空间 单位：KB
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 50, baos);
		byte[] b = baos.toByteArray();
		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitmap = zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i),
					bitmap.getHeight() / Math.sqrt(i));
		}
		return bitmap;
	}

	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}
	
	// bitmap转byte[]
	public static byte[] BitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
	
	// 压缩文件（例如图片） --->返回要判断是否为null
	public static File compressImg(File file, long size, Context context) throws IOException {
		String orientation = "";
		int angle = 0;
		Bitmap mBitmap = null;
		Bitmap tmpBitmap = null;
		OutputStream os = null;
		Bitmap btm = null;

		// 文件不存在
		if (!file.exists()) {
			return null;
		}

		String filepath = file.getAbsolutePath();
		orientation = ImageUtils.getOrientation(filepath);

		// 若文件小于指定大小，则不进行压缩
		if (file.length() > size) {
			try {
				String path = Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/"+ context.getResources().getString(R.string.app_name_en) +"/cache/save/";
				File tmpfile = new File(path);
				if (!tmpfile.exists()) {
					tmpfile.mkdirs();
				} 
				tmpfile = new File(path, "tmp.jpg");

				while (file.length() > size) {
					
					BitmapFactory.Options opts = new BitmapFactory.Options();
					// 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
					opts.inSampleSize = 2;
					// inJustDecodeBounds设为false表示把图片读进内存中
					opts.inJustDecodeBounds = false;
					// 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
					btm = BitmapFactory
							.decodeFile(file.getAbsolutePath(), opts); 

					// 创建文件输出流
					if (btm == null) {
						return file;
					}

					tmpfile = new File(path, "tmp.jpg");
					os = new FileOutputStream(tmpfile);
					// 存储
					btm.compress(CompressFormat.JPEG, 100, os);
					// 关闭流
					os.flush();   
					os.close();  
					if (btm != null && !btm.isRecycled()) {
						btm.recycle(); 
					}  
					file = new File(path + file.getName());
					tmpfile.renameTo(file);
				}
			} catch (Exception e) {
				Log.e("compressImg",e.getMessage());
				return null;
			}
		}
		
		return file;
	}

	/**
	 * 读取图片的旋转的角度
	 *
	 * @param path 图片绝对路径
	 * @return 图片的旋转角度
	 */
	public static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 将图片按照某个角度进行旋转
	 *
	 * @param bm     需要旋转的图片
	 * @param degree 旋转角度
	 * @return 旋转后的图片
	 */
	private static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}


	/**
	 * 压缩图片
	 *
	 * @param image
	 * @return
	 */
	public static Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		image.compress(CompressFormat.JPEG, 100, baos);
		int options = 100;
		// 循环判断如果压缩后图片是否大于250K,大于继续压缩
		while (baos.toByteArray().length / 1024 > 1024 && options > 10) {
			// 重置baos
			baos.reset();
			// 这里压缩options%，把压缩后的数据存放到baos中
			image.compress(CompressFormat.JPEG, options, baos);
			// 每次都减少10
			options -= 10;
		}
		// 把压缩后的数据baos存放到ByteArrayInputStream中
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		// 把ByteArrayInputStream数据生成图片
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
		Log.d("baos.toByteArray()", baos.toByteArray().length + "");
		return bitmap;
	}

	/**
	 * 截取scrollview的屏幕
	 *
	 * @param scrollView
	 * @return 用法实例 ScreenUtils.savePic(XXXActivity.this,ScreenUtils.compressImage(ScreenUtils.getBitmapByView(XXXScrollView)));
	 */
	public static Bitmap getBitmapByView(ScrollView scrollView) {
		int h = 0;
		Bitmap bitmap = null;
		// 获取scrollview实际高度
		for (int i = 0; i < scrollView.getChildCount(); i++) {
			h += scrollView.getChildAt(i).getHeight();
			scrollView.getChildAt(i).setBackgroundColor(
					Color.parseColor("#ffffff"));
		}
		// 创建对应大小的bitmap
		bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Config.ARGB_8888);
		final Canvas canvas = new Canvas(bitmap);
		scrollView.draw(canvas);
		return bitmap;
	}

	/**
	 * 保存到sdcard
	 *
	 * @param b
	 * @return
	 */
	public static String savePic(Context context, Bitmap b) {
		File outfile = new File(BaseConstants.CACHE_SAVE_IMG_PATH);
		FileUtils.delFile(outfile); //删除上次的
		// 如果文件不存在，则创建一个新文件
		if (!outfile.isDirectory()) {
			try {
				outfile.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String fname = outfile + "/" + System.currentTimeMillis() + ".jpg";
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(fname);
			if (null != fos) {
				b.compress(CompressFormat.JPEG, 90, fos);
				fos.flush();
				fos.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 其次把文件插入到系统图库
		try {
			MediaStore.Images.Media.insertImage(context.getContentResolver(), fname, fname, null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 最后通知图库更新
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fname)));
		return fname;
	}

	//获取所有图片
	public static ArrayList<String> get(Context context) {
		ArrayList<String> paths = new ArrayList<>();
		Cursor cursor = context.getContentResolver().query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI
				, null
				, null
				, null
				, MediaStore.Images.Media.DATE_MODIFIED + " ASC");
		while (cursor.moveToNext()) {
			//获取图片的名称
			String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
			//获取图片的生成日期
			byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
			//获取图片的详细信息
			String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
//            System.out.println(name);
//            System.out.println(desc);
			paths.add(new String(data, 0, data.length - 1));
		}
		return paths;
	}

	public static void notifySys(Context context, File file) {
		// 其次把文件插入到系统图库
		try {
			Uri uri = FileProvider
					.getUriForFile(context
							, context.getApplicationContext().getPackageName() + ".provider"
							, file);
			MediaStore.Images.Media.insertImage(context.getContentResolver(),
					file.getAbsolutePath(), file.getName(), null);
			// 最后通知图库更新
			context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}